package velha.connection.net;

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.*;
import velha.VelhaMIDlet;
import velha.game.Constantes;
import velha.game.Player;
import velha.game.Rival;
import velha.game.VelhaCanvas;

public class NETCliente implements CommandListener, Runnable {

    private TextBox campoIp = new TextBox("Endereço IP:", null, 15, TextField.ANY);
    private Command backCommmand = new Command("Voltar", Command.BACK, 0);
    private Command connectCommand = new Command("Conectar", Command.OK, 1);
    private VelhaMIDlet midlet;
    //
    private boolean conexaoCancelada;

    public NETCliente(VelhaMIDlet midlet) {
        this.midlet = midlet;

        campoIp.addCommand(backCommmand);
        campoIp.addCommand(connectCommand);
        campoIp.setCommandListener(this);
    }

    public void showGUI() {
        midlet.getDisplay().setCurrent(campoIp);
    }

    public void commandAction(Command c, Displayable d) {
        if (c == backCommmand) {
            conexaoCancelada = true;
            midlet.getDisplay().setCurrent(new NETMenu(midlet));
        } else if (c == connectCommand) {
            new Thread(this).start();
        }
    }

    public void run() {

        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Alert alerta = new Alert("Erro", "Thread interrompida" + ex, null, AlertType.ERROR);
            alerta.setTimeout(Alert.FOREVER);
            midlet.getDisplay().setCurrent(alerta);
        }

        if (conexaoCancelada) {
            return;
        }

        try {
            SocketConnection conn = (SocketConnection) Connector.open("socket://" + campoIp.getString() + ":5542");

            ////if (conexaoCancelada) {
             //   conn.close();
               // return;
            //}
            
            Player jogador = new Player();
            jogador.caracter = Constantes.CARACTER_PLAYER_2;
            jogador.isPlayer1 = false;
            jogador.isPrimeiro = false;

            jogador.pontos = 0;

            Rival rival = new Rival();
            rival.caracter = Constantes.CARACTER_PLAYER_1;
            rival.id = 1;

            rival.pontos = 0;

            VelhaCanvas game = new VelhaCanvas(midlet, jogador, rival);

            game.in = conn.openDataInputStream();
            game.out = conn.openDataOutputStream();

            game.lapis.isVisivel = false;

            midlet.getDisplay().setCurrent(game);

            game.startMessageProcessing();
        } catch (IOException ex) {
            Alert alerta = new Alert("Erro", "Problema ao conectar " + ex, null, AlertType.ERROR);
            alerta.setTimeout(Alert.FOREVER);
            midlet.getDisplay().setCurrent(alerta);
        }
    }
}
